package com;

import com.itheima.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class UserTest {
    public static void main(String[] args) {
        // 读取文件名
        String resources = "mybatis-config.xml";
        // 创建流
        Reader reader = null;
        try {
            // 读取 mybatis-config.xml 文件内容到 reader 对象中
            reader = Resources.getResourceAsReader(resources);
        } catch (IOException e) {
            e.printStackTrace();
            return; // 如果文件读取失败，直接退出程序
        }

        // 初始化 MyBatis 数据库，创建 SqlSessionFactory 类的实例
        SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);

        // 创建 SqlSession 实例
        try (SqlSession session = sqlMapper.openSession()) {

            // 增加用户
            User newUser = new User();
            newUser.setUid(2);  // 请确保uid是唯一的
            newUser.setUname("Bob");
            newUser.setUage(30);
            session.insert("insertUser", newUser);
            session.commit();
            System.out.println("User added: " + newUser.getUname());

            // 查询单个用户
            User user = session.selectOne("findById", 2);
            if (user != null) {
                System.out.println("User found: " + user.getUname());
            } else {
                System.out.println("User not found with id 2");
            }

            // 更新用户
            user.setUname("Bob Updated");
            user.setUage(31);
            session.update("updateUser", user);
            session.commit();
            System.out.println("User updated: " + user.getUname());

            // 查询所有用户
            List<User> users = session.selectList("selectList");
            System.out.println("All users:");
            for (User u : users) {
                System.out.println(u.getUid() + ": " + u.getUname() + ", " + u.getUage());
            }

            // 删除用户
            session.delete("deleteUser", 2);
            session.commit();
            System.out.println("User with id 2 deleted");

        } catch (Exception e) {
            // 捕获可能的异常并打印堆栈信息
            e.printStackTrace();
        }
    }
}
